package com.gt.login.activities;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.gt.login.Constants;
import com.gt.login.DomContentAppend;
import com.gt.login.R;
import com.gt.login.Session;
import com.gt.login.User;

public class UserDetailViewEdit extends Activity {
	TextView welComeLbl;
	EditText fnameTxt;
	EditText lnameTxt;
	EditText addrTxt;
	EditText phoneTxt;
	User previousUserData;
	String XML_FILE = Constants.XML_FILE;
	String OP_DATA_PATH = Constants.OP_DATA_PATH;
	boolean isEntry;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.userdetailentry);
		initComponents();
		processBundleValue();
	}

	@Override
	public void onBackPressed() {
		handleBackPress();
	}

	/**
	 * onCreateOptionsMenu is called only once
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.entry_form_menu, menu);
		return true;
	}

	/**
	 * Since, onCreateOptionsMenu is called only once use onPrepareOptionsMenu
	 */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// disable save menu
		// if (!isEntry) {
		// //disable save menu
		// menu.getItem(0).setEnabled(false);
		// }
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.backMnu:
			handleBackPress();
			return true;
		case R.id.saveDataMnu:
			User user = getFormData();
			if(user.equals(previousUserData)){
				showToast("Nothing to Save");
				return false;
			}
			if (saveUserDetail()) {
				handleSuccessSave();
			} else {
				showError();
			}
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void handleBackPress() {
		if (!isEntry && previousUserData.equals(getFormData())) {
			finish();
		} else {

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("There are unsaved changes,\nSure to Exit ?")
					.setPositiveButton("Yes", backPressDiOnClickL)
					.setNegativeButton("No", backPressDiOnClickL).show();
		}
	}

	DialogInterface.OnClickListener backPressDiOnClickL = new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case DialogInterface.BUTTON_POSITIVE:
				finish();
				break;

			case DialogInterface.BUTTON_NEGATIVE:
				// No button clicked
				break;
			}
		}
	};

	private void processBundleValue() {
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			// but extra cannot be null
			isEntry = extras.getBoolean("ISENTRY");
			if (isEntry) {
				welComeLbl.setText("Enter the Details.");
			} else {
				previousUserData = (User) extras.get("USER");
				displayUserDetail();

			}
		}

	}

	private void disableForm() {
		TextWatcher tw = new UnEditableTextWatcher();
		fnameTxt.addTextChangedListener(tw);
		lnameTxt.addTextChangedListener(tw);
		addrTxt.addTextChangedListener(tw);
		phoneTxt.addTextChangedListener(tw);
	}

	private void displayUserDetail() {
		// read details
		welComeLbl.setText("Details of " + previousUserData.getUserName());
		fnameTxt.setText(getNotNull(previousUserData.getFirstName()));
		lnameTxt.setText(getNotNull(previousUserData.getLastName()));
		addrTxt.setText(getNotNull(previousUserData.getAddress()));
		phoneTxt.setText(getNotNull(previousUserData.getPhoneNo()));

	}

	private void initComponents() {
		welComeLbl = (TextView) findViewById(R.id.welcomeMsgLBL);
		fnameTxt = (EditText) findViewById(R.id.fnameTxt);
		lnameTxt = (EditText) findViewById(R.id.lnameTxt);
		addrTxt = (EditText) findViewById(R.id.addrTxt);
		phoneTxt = (EditText) findViewById(R.id.phoneTxt);
	}

	private String getNotNull(String suspect) {
		if (suspect == null) {
			return "-";
		}
		return suspect;
	}

	private void showError() {
		// dialog at success

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Edit Failed")
				.setPositiveButton("OK", saveFailDiOnClickL).show();

	}

	DialogInterface.OnClickListener saveFailDiOnClickL = new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int which) {
		}
	};

	private boolean saveUserDetail() {
		User user = getFormData();
		DomContentAppend dca = new DomContentAppend(XML_FILE, OP_DATA_PATH
				+ getDate() + user.getUserName().trim() + "_.xml");
		return dca.editUser(user);

	}
	private void showToast(String msg) {
		Toast toast;
		toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0);
		toast.show();
	}
	private void handleSuccessSave() {
		// dialog at success
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Edit Success")
				.setPositiveButton("OK", saveSuccessDiOnClickL).show();

	}

	DialogInterface.OnClickListener saveSuccessDiOnClickL = new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			finish();
		}
	};

	private User getFormData() {
		User user = new User();
		// TODO: add form input for usrname and password also
		// currently set username,password from session
		Session ss = ((Session) getApplicationContext());
		User u = ss.getLoggedInUser();
		user.setUserName(u.getUserName());
		user.setPassword(u.getPassword());
		// read value from form
		user.setAddress(addrTxt.getText().toString().trim());
		user.setFirstName(fnameTxt.getText().toString().trim());
		user.setLastName(lnameTxt.getText().toString().trim());
		user.setPhoneNo(phoneTxt.getText().toString().trim());
		return user;
	}

	private static String getDate() {
		DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss_");
		Date date = new Date();
		return dateFormat.format(date);
	}

	private class UnEditableTextWatcher implements TextWatcher {

		@Override
		public void afterTextChanged(Editable s) {
			// do nothing
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
		}
	}
}
